import { createRouter, createWebHashHistory } from 'vue-router'
import OrderPage from '@/views/OrderPage.vue'
import BindPage from '@/views/BindPage.vue'
import QueryPage from '@/views/QueryPage.vue'
import ListPage from '@/views/ListPage.vue'
import CardPage from '@/views/CardPage.vue'
import SignPage from '@/views/SignPage.vue'
import OrderItems from '@/views/OrderItems.vue'
import View from '@/views/View.vue'
import { showToast } from 'vant'
import service from '@/api'

const routes = [
  // {
  //   path: '/',
  //   redirect: '/list'
  // },
  {
    path: '/order',
    name: 'Order',
    component: OrderPage,
    meta: { requiresAuth: true }
  },
  {
    path: '/bind',
    name: 'Bind',
    component: BindPage
  },
  {
    path: '/query',
    name: 'Query',
    component: QueryPage,
    meta: { requiresAuth: true }
  },
  {
    path: '/list',
    name: 'List',
    component: ListPage,
    meta: { requiresAuth: true }
  },
   {
    path: '/card',
    name: 'Card',
    component: CardPage,
    meta: { requiresAuth: true }
  },
   {
    path: '/order-sign',
    name: 'order-sign',
    component: OrderItems,
    meta: { requiresAuth: true }
  },
   {
    path: '/sign',
    name: 'Sign',
    component: SignPage,
    meta: { requiresAuth: false }
  },{
    path:'/view',
    name:'View',
    component:View
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  const tempInfo = localStorage.getItem('userInfo');


  const userInfo = tempInfo == 'undefined' ? {} : JSON.parse(localStorage.getItem('userInfo'))


  let openId = new URLSearchParams(window.location.search).get('openId');
  if (!openId) {
    let src = window.location.href;
    let index = src.indexOf("?");
    if (index > 0) {
      let dataStr = src.substring(src.indexOf("?") + 1);
      let dataArray = dataStr.split("&");

      dataArray.forEach(str => {
        let param = str.split("=");
        if (param[0] == 'openId') {
          openId = param[1];
        }
      })

    }

  }
  let orderNo = '';
  if (!orderNo) {
    let src = window.location.href;
    let index = src.indexOf("?");
    if (index > 0) {
      let dataStr = src.substring(src.indexOf("?") + 1);
      let dataArray = dataStr.split("&");

      dataArray.forEach(str => {
        let param = str.split("=");
        if (param[0] == 'orderNo') {
          orderNo = param[1];
        }
      })

    }
  }


  if (userInfo) {
    let id = userInfo.openid;
    //if(openId!=id){
    const res = await service.getUSERByOpenId({
      itype: "customer_query",
      info: { openId: openId, },
    });
    // 如果用户已绑定,存储用户信息,否则跳转到绑定页面
    if (res.data?.isBind) {
      localStorage.setItem('userInfo', JSON.stringify(res.data));
      userInfo.isBind = true;
    } else {
      localStorage.setItem('userInfo', JSON.stringify(res.data));
      userInfo.isBind = false;
    }
    // }
  } else {
    const res = await service.getUSERByOpenId({
      itype: "customer_query",
      info: { openId: openId, },
    });
    // 如果用户已绑定,存储用户信息,否则跳转到绑定页面
    if (res.data?.isBind) {
      localStorage.setItem('userInfo', JSON.stringify(res.data));
      //userInfo.isBind=true;
    } else {
      localStorage.setItem('userInfo', JSON.stringify(res.data));
      //userInfo.isBind=false;
    }
  }
  let target = to.path
  localStorage.getItem('userInfo');
  const tempInfo2 = localStorage.getItem('userInfo');
  const userInfo1 =tempInfo2=='undefined'?{}: JSON.parse(localStorage.getItem('userInfo'));

  if (to.meta.requiresAuth && !userInfo1.isBind) {
    if (!openId) {
      showToast('非法访问,请求无openId！')
      return;
    }
    next({
      name: 'Bind',
      query: { openId, target }
    })
  } else if (to.name === 'Bind' && userInfo1.isBind) {
    next({ name: 'Order', query: { openId } })
  }
  else if (to.hash.indexOf("query") > 0 && userInfo1.isBind && orderNo) {
    next({ name: 'Query', query: { openId, orderNo } })
  }
  else if (to.hash.indexOf("query") > 0 && userInfo1.isBind) {
    next({ name: 'Query', query: { openId } })
  }  
  else if (to.hash.indexOf("list") > 0 && userInfo1.isBind) {
    next({ name: 'List', query: { openId } })
  } else {
    next()
  }
})

export default router